<?php
/**
 * Class rail_user
 *
 * A rail_user is used to manage users and handle user profiles. Each rail_user has an unique name, the group is his
 * primary rail_group. A user can be a member of some groups.
 * There are two special users who can't be deleted or rename, root and guest. The password for the guest user can't change.
 *
 **
 * rail_object
 *   |
 *   + rail_user
 *
 * PHP versions 5
 * See http://www.open-rail.org for more informations.
 *
 **
 * Copyright (C)
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
 * of ERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software
 * Fundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
 *
 **
 * @author Bastian Che Schröder <bastian@open-rail.org>
 * @version 2009-09-11
 * @package rail
 */
class rail_user extends rail_object {

	/**
	 * Attributes which are not writeable from outside. Outside means by calling set_attribute(s) method.
	 * The array contains only the name of protected attributes not the attribute itself.
	 *
	 * @var array
	 */
	protected $protected_attributes = array( OBJ_TIME_CREATE, OBJ_TIME_LASTWRITE, OBJ_NAME, RAIL_PASSWD );

	/**
	 * Relations which are not writeable from outside. Outside means by calling set_relation or remove_relation method.
	 * The array contains only the name of protected relation not the object associated with the relation.
	 *
	 * @var array
	 */
	protected $protected_relations = array( RAIL_MEMBERSHIP );


	/**
	 * Copy rail_user to environment. Set the name for the new rail_user to unique one.
	 *
	 * @param rail_object $pEnvironment
	 * @param bool $pRecursive (optional)
	 * @return rail_user
	 */
	public function copy ( $pEnvironment, $pRecursive ) {
		$copy = parent::copy( $pEnvironment, $pRecursive );

		// update OBJ_NAME beacause two users can't have the same name
		$this->rail_connector->send_request( "UPDATE " . $this->rail_connector->mysql_table_prefix . "objects_attributes SET value='" . $copy->get_name() . "_" . $copy->get_id() . "' WHERE `object`=" . $copy->get_id() . " AND `attribute`='OBJ_NAME' LIMIT 1" );

		return new rail_user( $this->rail_connector, $copy->get_id() );
	}

	
	/**
	 * Create a new rail_user. A valid rail_user must has a unique name and a password.
	 *
	 * @exception rail_exception
	 * @param rail_connector $pRailConnector
	 * @param rail_object $pEnvironment
	 * @param string $pName OBJ_NAME
	 * @param string $pPasswd RAIL_PASSWD
	 * @return rail_user
	 */
	public static function create ( $pRailConnector, $pEnvironment, $pName = '', $pPasswd = '' ) {
		// check wheather name is empty
		if( strlen( trim( $pName) ) == 0 )
			throw new rail_exception( null, 'Cany\'t create new user without a name!' );
		// check wheather passwd is empty
		if( strlen( trim( $pPasswd) ) == 0 )
			throw new rail_exception( null, 'Can\'t create new user without a password!' );
		// check wheather the name already exist
		$data = $pRailConnector->send_request( "
			SELECT
				" . $pRailConnector->mysql_table_prefix . "objects.`id`,
				" . $pRailConnector->mysql_table_prefix . "objects_attributes.`value` as `name`
			FROM
				" . $pRailConnector->mysql_table_prefix . "objects,
				" . $pRailConnector->mysql_table_prefix . "objects_attributes
			WHERE
				" . $pRailConnector->mysql_table_prefix . "objects.`id`=" . $pRailConnector->mysql_table_prefix . "objects_attributes.`object` AND
				" . $pRailConnector->mysql_table_prefix . "objects_attributes.`attribute`='OBJ_NAME' AND
				" . $pRailConnector->mysql_table_prefix . "objects.`type`='RAIL_USER'
		" );
		while( ($data_row = $data->fetch_assoc()) ){
			if( $data_row['name'] != $pName )
				continue;

			throw new rail_rail_exception( null, "Can't create user: $pName already exist!" );
		}
		
		$object = parent::create( $pRailConnector, $pEnvironment, $pName );

		// set user to created user
		$pRailConnector->send_request( "
			UPDATE " . $pRailConnector->mysql_table_prefix . "objects SET `type`='RAIL_USER' WHERE `id`=" . $object->get_id() ."
			UPDATE " . $pRailConnector->mysql_table_prefix . "objects SET `user`='" . $object->get_id() . "' WHERE id='" . $object->get_id() . "' LIMIT 1;
			UPDATE " . $pRailConnector->mysql_table_prefix . "objects SET `mode`='110110000' WHERE id='" . $object->get_id() . "' LIMIT 1;
			INSERT INTO " . $pRailConnector->mysql_table_prefix . "objects_attributes (`object`,`attribute`,`value`) VALUES ('" . $object->get_id() . "','RAIL_PASSWD','" . rtrim( md5( $pPasswd ) ) . "')
		" );

		return $object;
	}

	
	/**
	 * Delete this rail_user. Change the primary user to root for all rail_object has this user as primary user.
	 * You are not able to delte the root or guest user.
	 *
	 * @exception rail_writepermission_exception
	 */
	public function delete () {
		// throw an exception if trying to deleting currently logedin user
		if( $this->rail_connector->get_user()->get_id() == $this->get_id() )
			throw new rail_writepermission_exception( $this, $this->rail_connector->get_user(), 'The actual loged in rail_user can\'t deleted.' );
		// throw an exception if trying to delete the root or guest user
		if( $this->get_name() == 'root' || $this->get_name() == 'guest' )
			throw new rail_writepermission_exception( $this, $this->rail_connector->get_user(), 'Can\'t delete ' . $this->get_name() . '.' );

		// get root users rail_id
		$data = $this->rail_connector->send_request( "
			SELECT
				" . $this->rail_connector->mysql_table_prefix . "objects.`id`
			FROM
				" . $this->rail_connector->mysql_table_prefix . "objects,
				" . $this->rail_connector->mysql_table_prefix . "objects_attributes
			WHERE
				" . $this->rail_connector->mysql_table_prefix . "objects.`id`=" . $this->rail_connector->mysql_table_prefix . "objects_attributes.`object` AND
				" . $this->rail_connector->mysql_table_prefix . "objects.`type`='RAIL_USER' AND
				" . $this->rail_connector->mysql_table_prefix . "objects_attributes.`attribute`='OBJ_NAME' AND
				" . $this->rail_connector->mysql_table_prefix . "objects_attributes.`value`='root'
			LIMIT
				1
		" )->fetch_assoc();
		$rail_id = $data['id'];

		// change user for all rail_objects owned by deleted user to root
		$this->rail_connector->send_request( "UPDATE " . $this->rail_connector->mysql_table_prefix . "objects SET `user`='$rail_id' WHERE `user`='" . $this->get_id() . "' AND `id`<>'" . $this->get_id() . "'" );

		return parent::delete();
	}


	/**
	 * Get all rail_group objects with a RAIL_MEMBERSHIP relation to this rail_user.
	 *
	 * @exception rail_readpermission_exception
	 * @return array
	 */
	public function get_memberships () {
		// check read permission
		if( !$this->is_readable() )
		 	throw new rail_readpermission_exception( $this, $this->rail_connector->get_user() );

		return array_merge( array($this->get_group()), $this->get_relations( RAIL_MEMBERSHIP ) );
	}


	/**
	 * Get password md5 crypted.
	 *
	 * @return string
	 */
	public function get_passwd () {
		return $this->get_attribute( RAIL_PASSWD );
	}


	/**
	 * Set a unique name for this rail_user. Throw an exception if the name already exist.
	 * You are not able to rename the root or guest user.
	 *
	 * @exception rail_writepermission_exception
	 * @param string $pName.
	 */
	public function rename ( $pName ) {
		// check write permission
		if( !$this->is_writeable() )
		 	throw new rail_writepermission_exception( $this, $this->rail_connector->get_user() );

		$name = trim( $pName );

		if( $this->cache[ 'attributes' ][ OBJ_NAME ] == $name )
			return;

		// can't rename root or guest account
		if( $this->get_name() == 'root' || $this->get_name() == 'guest' )
			throw new rail_writepermission_exception( $this, $this->rail_connector->get_user(), 'Can\'t rename ' . $this->get_name() . '.' );

		// check wheather the new name already exist
		$data = $this->rail_connector->send_request( "
			SELECT
				" . $this->rail_connector->mysql_table_prefix . "objects.`id`,
				" . $this->rail_connector->mysql_table_prefix . "objects_attributes.`value` as `name`
			FROM
				" . $this->rail_connector->mysql_table_prefix . "objects,
				" . $this->rail_connector->mysql_table_prefix . "objects_attributes
			WHERE
				" . $this->rail_connector->mysql_table_prefix . "objects.`id`=" . $this->rail_connector->mysql_table_prefix . "objects_attributes.`object` AND
				" . $this->rail_connector->mysql_table_prefix . "objects_attributes.`attribute`='OBJ_NAME' AND " . $this->rail_connector->mysql_table_prefix . "objects.`type`='RAIL_USER'
		" );
		while( ($data_row = $data->fetch_assoc()) ){
			if( $data_row['name'] != $name )
				continue;

			throw new rail_writepermission_exception( $this, $this->rail_connector->get_user(), "Rename failed. User $name already exist!" );
		}

		// set new name
		$this->set_attribute( OBJ_NAME, $name );
	}


	/**
	 * Set the password for this user. The guest users password can't change.
	 *
	 * @exception rail_writepermission_exception
	 * @param string $pPasswd
	 */
	public function set_passwd ( $pPasswd ) {
		// check write permission
		 if( !$this->is_writeable() )
		 	throw new rail_writepermission_exception( $this, $this->rail_connector->get_user() );
		// check if trying to change guest users password
		if( $this->get_name() == 'guest' )
			throw new rail_writepermission_exception( $this, $this->rail_connector->get_user(), 'Can\'t change guest\'s password!' );

		// set new passwd
		$this->set_attribute( RAIL_PASSWD, md5( $pPasswd ) );
	}

} // End of rail_user
?>